package com.cmes.system.web.controller;

import com.cmes.core.annotation.OperateLog;
import com.cmes.core.context.security.SecurityContextHolder;
import com.cmes.core.utils.BeanUtils;
import com.cmes.system.api.bo.UpdatePasswordBO;
import com.cmes.system.api.bo.UserProfileBO;
import com.cmes.system.core.entity.UserEntity;
import com.cmes.system.core.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * 用户中心
 *
 * @author Bruce.Gong
 * @since 1.0.0-SNAPSHOT
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/ucenter")
public class UcenterController {

    private final String MODULE = "用户中心";
    private final UserService userService;

    @PostMapping("profile")
    public UserEntity profile() {
        return userService.getById(SecurityContextHolder.getCurrentUserId());
    }

    @OperateLog(module = MODULE, businessType = "UPDATE_PROFILE")
    @PostMapping("updateProfile")
    public void updateProfile(@RequestBody @Valid UserProfileBO bo) {
        UserEntity user = BeanUtils.copyProperties(bo, new UserEntity());
        user.setId(SecurityContextHolder.getCurrentUserId());
        userService.canUpdateProfile(user);
        userService.update(user);
    }

    @OperateLog(module = MODULE, businessType = "UPDATE_PASSWORD")
    @PostMapping("updatePassword")
    public void updatePassword(@RequestBody @Valid UpdatePasswordBO bo) {
        userService.updatePassword(SecurityContextHolder.getCurrentUserId(), bo.getOldPwd(), bo.getNewPwd());
    }

}
